/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trick.it.admin.cell;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 *
 * @author takahara
 */
public class KeywordListViewCell extends ListCell<String>{
    
    private TextField textField;
    
    private final ContextMenu contextMenu = new ContextMenu();

    public KeywordListViewCell() {

        // コンテキストメニューの初期化
        MenuItem deletePageMenuItem = new MenuItem("削除");

        contextMenu.getItems().addAll(deletePageMenuItem);

        // ---------------------------------------------------------------------
        // 削除イベント
        // ---------------------------------------------------------------------
        deletePageMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                getListView().getItems().remove(getItem());
            }
        });
    }

    /**
     * セル更新
     *
     * @param item
     * @param empty
     */
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            super.setText(item);

            // コンテキストメニュー
            setContextMenu(contextMenu);

        }
    }
    
    @Override
    public void startEdit() {
        super.startEdit();

        if (textField == null) {
            createTextField();
        }
        setText(null);
        setGraphic(textField);
        textField.selectAll();
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getItem());
        setGraphic(null);
    }
    
    private void createTextField() {
        textField = new TextField(getItem());
        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.ENTER) {
                    commitEdit(textField.getText());
                } else if (t.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }
            }
        });
    }
}
